<template>
  <div class="container">
    <div class="index-header">
      <img src="../assets/images/logoB.png"
           v-if="logoFlag">
      <img :src="logoUrl"
           v-if="!logoFlag">
      <div class="sliderBtn"
           @click="dialogBtn"
           style="display: none;">
        <img src="../assets/images/slidBtn.png">
      </div>
    </div>
    <router-link class="project-active"
                 to="/modifyProject">
      {{premisesName}}
      <i class="fa fa-angle-right"></i>
    </router-link>
    <div class="information-number">
      <ul class="info-list">
        <router-link tag="li"
                     :to="{ path: '/confirmList', query: {customerStatus: '0'}}"
                     v-res="menu_0008_0000"
                     v-if="indexRes.menu_0008_0000">
          <p class="title">报备待审</p>
          <p class="number">{{homePageInfo.auditCount}}</p>
        </router-link>
        <router-link tag="li"
                     :to="{ path: '/confirmList', query: {customerStatus: '10'}}"
                     v-res="menu_0008_0001"
                     v-if="indexRes.menu_0008_0001">
          <p class="title">到访待审</p>
          <p class="number">{{homePageInfo.visitAuditCount}}</p>
        </router-link>
        <router-link tag="li"
                     to="/distList"
                     v-res="menu_0008_0002"
                     v-if="indexRes.menu_0008_0002">
          <p class="title">已到访</p>
          <p class="number">{{homePageInfo.distCount}}</p>
        </router-link>
        <router-link tag="li"
                     to="/complaintHandling"
                     v-res="menu_0008_0003"
                     v-if="indexRes.menu_0008_0003">
          <p class="title">申诉处理</p>
          <p class="number">{{homePageInfo.appealCount}}</p>
        </router-link>
      </ul>
    </div>
    <div class="searchDiv">
      <div class="input-wrap">
        <p class="input-text"
           @click="clickDiv"><i class="fa fa-search"></i>请输入完整的客户姓名或电话</p>
      </div>
    </div>
    <ul class="entry-list">
      <li v-res="menu_0008_0004"
          v-if="indexRes.menu_0008_0004">
        <router-link to="/report"
                     class="entryBtn">
          <div class="entryBtn-icon">
            <span></span>
          </div>
        </router-link>
        <p class="entry-title">代报备</p>
      </li>
      <li @click="scanQRCode"
          v-res="menu_0008_0005"
          v-if="indexRes.menu_0008_0005">
        <a href="javascript:;"
           class="entryBtn">
          <div class="entryBtn-icon">
            <span class="icon-two"></span>
          </div>
        </a>
        <p class="entry-title">扫码确认</p>
      </li>
    </ul>
    <search-page v-if="thisShow"
                 msgFrom="thisShow"
                 v-on:cancel-search="cancelSearch"></search-page>
    <transition name="slipLeft">
      <div class="sidebar"
           v-if="showDialog">
        <div class="logo-name">
          <div class="logoV"
               v-if="exitLogo"></div>
          <div class="logoV"
               v-if="!exitLogo"
               v-bind:style="{'background': 'url('+exitLogoUrl+')'}"></div>
          <p class="userName">{{userName}}</p>
        </div>
        <ul class="sidebar-list">
          <router-link tag="li"
                       to="/modifyPassword">
            <i class="fa fa-lock leftIcon"></i>
            修改密码
            <i class="fa fa-angle-right rightIcon"></i>
          </router-link>
          <!--
                      	作者：353895897@qq.com
                      	时间：2017-04-24
                      	描述：此功能已经移动至首页
	  				<router-link tag="li" to="/modifyProject">
	  					<i class="fa fa-folder-open leftIcon"></i>
	  					修改项目
	  					<i class="fa fa-angle-right rightIcon"></i>
	  				</router-link>
	  				-->
        </ul>
        <a href="javascript:;"
           class="sign-out"
           @click="signOut">退出</a>
      </div>
    </transition>
    <div class="dialog-cover"
         @click="closeDialog"
         v-if="showDialog"></div>
  </div>
</template>
<script>
import SearchPage from "./base/searchPage.vue";
import { Toast } from "mint-ui";
import wx from "weixin-js-sdk";
export default {
  components: {
    SearchPage
  },
  data() {
    return {
      exitLogo: true,
      logoFlag: true,
      thisShow: false,
      showDialog: false,
      homePageInfo: {},
      logoUrl: "",
      exitLogoUrl: "",
      userId: window.localStorage.getItem("2_userId"),
      userName: window.localStorage.getItem("2_userName"),
      premisesIds: window.localStorage.getItem("2_premisesIds")
        ? window.localStorage.getItem("2_premisesIds").split(",")
        : ["-1"],
      premisesName: window.localStorage.getItem("2_premisesName"),
      indexRes: {
        menu_0008_0000: false,
        menu_0008_0001: false,
        menu_0008_0002: false,
        menu_0008_0003: false,
        menu_0008_0004: false,
        menu_0008_0005: false
      }
    };
  },
  mounted: function () {
    this.autoLogin();
    this.initHomePage();
    this.wxConfig();
    this.getCompanyLogo();
    if (!this.premisesName) {
      this.premisesName = "切换项目";
    }
    this.initStyle();
    //初次进来权限加载跟不上页面渲染，权限没有生效，这里暂时这么处理。
    var res = JSON.parse(window.sessionStorage.getItem("2_resources"));
    if (!res || res.length == 0) {
      let interval = setInterval(() => {
        res = JSON.parse(window.sessionStorage.getItem("2_resources"));
        if (res && res.length > 0) {
          clearInterval(interval);
          for (let index = 0; index < res.length; index++) {
            const item = res[index];
            if (this.indexRes.hasOwnProperty(item)) {
              this.indexRes[item] = true;
            }
          }
        }
      }, 500);
    } else {
      for (let index = 0; index < res.length; index++) {
        const item = res[index];
        if (this.indexRes.hasOwnProperty(item)) {
          this.indexRes[item] = true;
        }
      }
    }
  },
  methods: {
    getCompanyLogo() {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/getLogo";
      var body = {};
      body.params = { logoType: "3" };
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        if (data.result == "1") {
          _self.logoUrl = data.logoUrl;
          _self.logoFlag = false;
        }
      });
    },
    getExitLogo() {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/getLogo";
      var body = {};
      body.params = { logoType: "4" };
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        if (data.result == "1") {
          _self.exitLogoUrl = data.logoUrl;
          _self.exitLogo = false;
        }
      });
    },
    wxConfig() {
      //微信配置
      var currUrl = location.href.split("#")[0];
      var body = {};
      body.params = {
        url: currUrl
      };
      var url = this.utilHelper.apiUrl + "/api/js_ticket";
      this.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        wx.config({
          debug: false,
          appId: data.appid, // 必填，公众号的唯一标识
          timestamp: data.time, // 必填，生成签名的时间戳
          nonceStr: data.noncestr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名，见附录1
          jsApiList: ["scanQRCode"]
        });
      });
    },
    scanQRCode: function () {
      //微信扫码
      var _self = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          _self.$router.replace({
            path: "/customerDetails/" + result
          });
        }
      });
    },
    clickDiv() {
      this.thisShow = true;
    },
    cancelSearch(msg) {
      this.thisShow = msg;
    },
    dialogBtn() {
      this.getExitLogo();
      this.showDialog = true;
    },
    closeDialog() {
      this.showDialog = false;
    },
    initHomePage() {
      var _self = this;
      var body = {};
      body.params = {
        premisesIds: _self.premisesIds,
        version: window.sessionStorage.getItem("version"),
        allPremisesFlag:
          window.localStorage.getItem("2_premisesName") == "已选择全部楼盘"
      };
      var url = _self.utilHelper.apiUrl + "/api/getAssistantAppIndex";
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData; 
        var result = data.result;
        var errorMsg = data.resultMsg;
        if (result == 1) {
          _self.homePageInfo = data;
        } else {
          if (errorMsg) {
            Toast({
              message: errorMsg,
              position: "middle",
              duration: 2000
            });
          }
          window.localStorage.setItem("2_isLogin", false);
          _self.$router.replace({
            path: "/login"
          });
        }
      });
    },
    signOut() {
      var _self = this;
      var body = {};
      var params = { userId: window.localStorage.getItem("2_userId") };
      body.params = params;
      var url = _self.utilHelper.apiUrl + "/api/loginOut";
      _self.$http.post(url, body).then(
        (response) => {
          var data = response.body;
          window.localStorage.removeItem("2_isLogin");
          window.localStorage.removeItem("2_userId");
          _self.$router.replace({
            path: "/login"
          });
        },
        (response) => {}
      );
    },
    autoLogin() {
      var _self = this;
      var phone = window.localStorage.getItem("2_phone");
      var password = window.localStorage.getItem("2_password");
      // alert("index:phone->" + phone + ", password->" + password);
      var loginData = {};
      loginData.phone = phone;
      if (!password) {
        return;
      } else {
        loginData.password = password;
      }
      loginData.domain = window.location.href;
      loginData.wxOpenId = window.localStorage.getItem("2_wxOpenid");
      loginData.cooCompanyId = "";
      // 如果判断是历史遗留的名称，则把历史的premisesId刷入现在的楼盘集合中
      var premisesName = window.localStorage.getItem("2_premisesName");
      if (
        !premisesName.includes("未选择") &&
        !premisesName.includes("已选择")
      ) {
        var premisesId = window.localStorage.getItem("2_premisesId");
        var premisesIds = window.localStorage.getItem("2_premisesIds");
        if (premisesId && !premisesIds) {
          premisesIds = [premisesId];
          window.localStorage.setItem("2_premisesIds", premisesIds);
          _self.premisesIds = premisesIds;
        }
      }
      if (phone) {
        var body = {};
        body.params = loginData;
        var url = _self.utilHelper.apiUrl + "/api/login";
        _self.$http.post(url, body).then(
          (response) => {
            var data = response.body.resData;
            var result = data.result;
            var errorMsg = data.resultMsg;
            if (result == "1") {
              window.localStorage.setItem("2_userId", data.id);
              window.localStorage.setItem("2_userName", data.accountName);
              window.localStorage.setItem("2_password", loginData.password);
              window.localStorage.setItem("2_phone", data.phone);
              window.localStorage.setItem("2_isLogin", true);
              window.localStorage.setItem("2_userRole", data.userRoleId);
              window.localStorage.setItem("2_accountType", data.accountType);
              // _self.$router.replace({
              //   path: "/index"
              // });
            } else {
              layer.msg(errorMsg, {
                time: 1000
              });
            }
          },
          (response) => {
            // layer.msg('登陆超时', {
            //     time: 1000
            // });
          }
        );
      }
    },
    initStyle() {
      //设置样式
      let pNodes = document.getElementsByClassName("info-list");
      let subNodes = pNodes[0].children;
      let count = 0;
      let index = [];
      for (let i = 0; i < subNodes.length; i++) {
        if (subNodes[i].style.display == "block") {
          count++;
          index.push(i);
        }
      }
      if (count == 1) {
        subNodes[index[0]].style.width = "100%";
      } else if (count == 2) {
        subNodes[index[0]].style.width = "50%";
        subNodes[index[1]].style.width = "50%";
      }
      //扫码，代报备
      let bNodes = document.getElementsByClassName("entry-list");
      console.log(bNodes);
      let bsubNodes = bNodes[0].children;
      console.log(bsubNodes);
      let bcount = 0;
      let bindex = [];
      for (let j = 0; j < bsubNodes.length; j++) {
        if (bsubNodes[j].style.display == "block") {
          bcount++;
          bindex.push(j);
        }
      }
      console.log(bindex);
      if (bcount == 1) {
        bsubNodes[bindex[0]].style.width = "100%";
      }
    }
  }
};
</script>
<style scoped>
.index-header {
  background: url(../assets/images/bgIndex.png) no-repeat bottom center;
  height: 220px;
  background-size: 100% 114px;
  text-align: center;
  position: relative;
}
.index-header > img {
  width: 100px;
  height: 66px;
  margin-top: 88px;
}
.sliderBtn {
  position: absolute;
  left: 20px;
  top: 20px;
  width: 45px;
  height: 45px;
  overflow: hidden;
  display: block;
}
.sliderBtn img {
  width: 100%;
  height: 100%;
}
.information-number {
  padding: 28px 0;
}
.info-list li {
  float: left;
  width: 25%;
  text-align: center;
  border-right: 1px solid #d8d8d8;
  padding: 0 8px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 48px;
}
.info-list li:last-child {
  border-right: none;
}
.info-list li .title {
  font-size: 14px;
  color: #8d8d8d;
  line-height: 20px;
}
.info-list li .number {
  color: #333;
  font-weight: bold;
  line-height: 14px;
  font-size: 14px;
}
.info-list li > p {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.searchDiv {
  height: 55px;
  background-color: #f8f5f3;
  padding: 10px;
  position: relative;
}
.searchDiv .input-wrap {
  width: 100%;
  height: 35px;
  border-radius: 40px;
  background-color: #e1c7c7;
}
.input-wrap .input-text {
  color: #fff;
  display: block;
  line-height: 35px;
  text-align: center;
}
.input-wrap .input-text .fa {
  margin-right: 10px;
  font-size: 18px;
}

.entry-list {
  margin-top: 26px;
  padding-bottom: 30px;
}
.entry-list li {
  float: left;
  width: 50%;
  text-align: center;
}
.entryBtn {
  width: 78px;
  height: 78px;
  border-radius: 80px;
  margin: 0 auto 15px;
  padding-top: 6px;
  display: block;
}
.entryBtn:focus {
  background-color: #fdefe5;
}

.entryBtn .entryBtn-icon {
  width: 66px;
  height: 66px;
  border-radius: 66px;
  background-color: #ef7d2e;
  margin: 0 auto;
  padding-top: 22px;
}
.entryBtn-icon span {
  width: 23px;
  height: 23px;
  display: block;
  background: url(../assets/images/iconA.png) no-repeat;
  background-position: 0 0;
  margin: 0 auto;
  background-size: 23px auto;
}
.entryBtn-icon .icon-two {
  background-position: 0 -23px;
}
.entryBtn-icon .icon-three {
  background-position: 0 -46px;
}
.entry-list .entry-title {
  color: #000;
  font-size: 16px;
}

.project-active {
  background-color: #fdefe5;
  height: 44px;
  line-height: 44px;
  padding: 0 30px 0 10px;
  position: relative;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.project-active .fa {
  position: absolute;
  right: 10px;
  font-size: 20px;
  color: #ed8b41;
  top: 12px;
}
/*侧边栏*/
.dialog-cover {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
.dialog-cover {
  background: #000;
  opacity: 0.3;
  z-index: 6;
}
.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 66;
  width: 80%;
  padding-top: 220px;
  z-index: 7;
}
.logo-name {
  position: absolute;
  top: 88px;
  left: 50%;
  text-align: center;
  margin-left: -50px;
  width: 100px;
}
.logo-name .logoV {
  width: 75px;
  height: 75px;
  border-radius: 100%;
  background: url(../assets/images/logoV.png) no-repeat center #eb6100;
  background-size: 54px auto;
  margin: 0 auto;
}
.logo-name .userName {
  color: #eb6100;
  font-size: 16px;
  padding-top: 16px;
}
.sidebar-list {
  padding-left: 10px;
}
.sidebar-list li {
  border-bottom: 1px solid #cdcdcd;
  padding: 8px 0;
  padding-left: 40px;
  line-height: 20px;
  height: 36px;
  position: relative;
  color: #333;
  margin-top: 8px;
  padding-right: 30px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
.sidebar-list .leftIcon {
  position: absolute;
  left: 10px;
  color: #eb6100;
  top: 8px;
  font-size: 20px;
}
.sidebar-list .rightIcon {
  position: absolute;
  right: 10px;
  font-size: 20px;
  top: 7px;
  color: #cecece;
}
.sign-out {
  width: 168px;
  height: 36px;
  background-color: #fbe7dd;
  border: 1px solid #fd893b;
  margin: 80px auto 0;
  display: block;
  text-align: center;
  line-height: 34px;
  border-radius: 60px;
  color: #6c2c00;
  font-size: 16px;
}

/*去浮动*/
.info-list:after,
.entry-list:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  overflow: hidden;
  font-size: 0;
  height: 0;
}
</style>